package com.sunny.myproject.sales.action;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.sunny.myproject.core.base.action.BaseAction;
import com.sunny.myproject.core.base.util.DateUtil;
import com.sunny.myproject.sales.entity.OtherSales;
import com.sunny.myproject.sales.service.OtherSalesService;

@Controller
@RequestMapping("/sales/otherSales")
public class OtherSalesAction extends BaseAction<OtherSales>{

	private Logger logger = Logger.getLogger(OtherSalesAction.class);
	
	private String title = "额外销售";
	
	@Autowired
	private OtherSalesService service;
	
	@Override
	@RequestMapping(params="list")
	public String list(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
	    	super.pager = super.pageStart(model, request,response, "sales/otherSales","otherSales",title);
	
	        super.pager = super.pageEnd(model, service.num(criterions), super.pager);
	
	        super.returnValue(model, service.find(criterions, pager));
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
		return "sales/otherSalesList";
	}

	@Override
	@RequestMapping(params="add")
	public String add(HttpServletRequest request, HttpServletResponse response) {
		super.add(title, request);
		return "sales/otherSalesEdit";
	}

	@Override
	@RequestMapping(params="edit")
	public String edit(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		super.returnValue(model, service.findById(super.edit(title, model, request)));
		return "sales/otherSalesEdit";
	}

	@Override
	@RequestMapping(params="delete")
	public String delete(HttpServletRequest request,
			HttpServletResponse response) {
		service.deleteByIds(super.param2(request));
		return "redirect:/sales/otherSales?list";
	}

	@Override
	@RequestMapping(params="save")
	public String save(HttpServletRequest request,
			HttpServletResponse response, @ModelAttribute OtherSales t) {
		service.save(t);
		return "redirect:/sales/otherSales?list";
	}

	@Override
	@RequestMapping(params="view")
	public String view(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		super.returnViewValue(model, service.findById(super.view(title, model, request)));
		return "sales/otherSalesEdit";
	}
	
	@RequestMapping(params="upload")
	public String upload(){
		return "sales/otherSalesUpload";
	}
	
	@RequestMapping(params="saveUpload")
	public String saveUpload(@RequestParam("file")MultipartFile file){
		try {
			InputStream is = file.getInputStream();

			// 创建xls文件对象
			HSSFWorkbook workbook = new HSSFWorkbook(is);
			HSSFSheet sheet = workbook.getSheetAt(0);// 取出第一个工作表
			logger.info("sheet_lastRowNum:"+sheet.getLastRowNum());
			// 开始循环遍历行，表头不处理
			for (int i = 1; i <= sheet.getLastRowNum(); i++) {
				// 获取行对象
				HSSFRow row = sheet.getRow(i);
				if (row == null) {
					break;
				}
				OtherSales t = new OtherSales();
				t.setName(row.getCell(0).getStringCellValue());
				t.setSaler(row.getCell(1).getStringCellValue());
				t.setShop(row.getCell(2).getStringCellValue());
				t.setPrice(Integer.parseInt(String.valueOf(row.getCell(3).getNumericCellValue()).replace(".0", "")));
				t.setRemark(row.getCell(4).getStringCellValue());
				t.setDate(DateUtil.formateStringDate(DateUtil.formatDateString(new Date())));
				service.save(t);
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return "sales/uploadSuccess";
	}

	@RequestMapping(params="chart")
	public String chart(Model model, HttpServletRequest request,
			HttpServletResponse response){
		super.criterions = new ArrayList<Criterion>();
		List<OtherSales> otherSales =service.list(criterions);
		String str = "";
		for (OtherSales otherSales2 : otherSales) {
			str +="{name:'"+otherSales2.getName()+"',data:["+otherSales2.getPrice()+"]},";
		}
		str = str.length()>0?str.substring(0, str.length()-1):"";
		model.addAttribute("series", str);
		return "sales/otherSalesChart";
	}
	@InitBinder
	public void initBinder(WebDataBinder binder){
		//注册定义的属性编辑器
		//1.日期
		 DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		 CustomDateEditor dateEditor = new CustomDateEditor(df, true);
		 //表示如果命令对象有date类型的属性,将使用该属性编辑器进行类型转换
		 binder.registerCustomEditor(Date.class, dateEditor);
	}

}
